/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/


#include "d3d_local.h"


/*-----------------------------------------------------------------------------
	Scene light stuff :
-----------------------------------------------------------------------------*/

//
//	ERSLightRenderer::ERSLightRenderer
//
ERSLightRenderer::ERSLightRenderer( ERScene *scene )
{
	LOG_INIT("Lighting engine");
	
	this->scene	=	scene;
	rtm			=	scene->rs->rtm;
	txm			=	scene->rs->txm;
	
	CONFIG_REGISTER_VAR( rs_skip_diffuse		, false );
	CONFIG_REGISTER_VAR( rs_skip_specular		, false );
	CONFIG_REGISTER_VAR( rs_white_diffuse		, false );
	//CONFIG_REGISTER_VAR( r_show_lighting	, false );
	//CONFIG_REGISTER_VAR( r_show_lights		, false );
	
	const uint SM_SIZE = 1024;

	sm_depth		=	scene->rs->rtm->AllocRenderTarget( RS_FORMAT_D16,		SM_SIZE, SM_SIZE );
	sm_color		=	scene->rs->rtm->AllocRenderTarget( RS_FORMAT_ARGB_U8, 	SM_SIZE, SM_SIZE );
	
	effect			=	NULL;
	
	ReloadShaders();
}


//
//	ERSLightRenderer::~ERSLightRenderer
//
ERSLightRenderer::~ERSLightRenderer( void )
{
	LOG_SHUTDOWN("Lighting engine");
	SAFE_RELEASE( effect );
}


//
//	ERSLightRenderer::ReloadShaders
//
void ERSLightRenderer::ReloadShaders( void )
{
	SAFE_RELEASE( effect );
	
	effect	=	scene->rs->CompileEffect("shaders/light.fx");
	
	if (!effect) {
		return;
	}

	//	get techniques :	
	tech_copy_depth	=	effect->GetTechniqueByName("tech_copy_depth");
	tech_ambient	=	effect->GetTechniqueByName("tech_ambient"	);
	tech_light		=	effect->GetTechniqueByName("tech_light"		);
	
	if (!tech_copy_depth	) LOG_WARNING("technique 'tech_copy_depth' not found");
	if (!tech_ambient		) LOG_WARNING("technique 'tech_ambient' not found");
	if (!tech_light			) LOG_WARNING("technique 'tech_light' not found");

	//	set rcp_screen_size :
	uint w,h;	
	scene->rs->GetScreenSize(w, h);
	effect->SetVector("rcp_screen_size", &D3DXVECTOR4(1.0f/w, 1.0f/h, 0,0));
}


/*-----------------------------------------------------------------------------
	Parameter's stuff :
-----------------------------------------------------------------------------*/

//
//	ERSLightRenderer::SetGBuffer
//
void ERSLightRenderer::SetGBuffer( IPxTexture *gbuffer, IPxTexture gbuffer_depth )
{
	if (!gbuffer) {
		this->gbuffer[0]	= NULL;
		this->gbuffer[1]	= NULL;
		this->gbuffer[2]	= NULL;
		this->gbuffer[3]	= NULL;
		this->gbuffer_depth	= NULL;
		return;
	}
	
	this->gbuffer[0]	= gbuffer[0];
	this->gbuffer[1]	= gbuffer[1];
	this->gbuffer[2]	= gbuffer[2];
	this->gbuffer[3]	= gbuffer[3];
	this->gbuffer_depth	= gbuffer_depth;
}


//
//	ERSLightRenderer::SetupGBufferSamplers
//
void ERSLightRenderer::SetupGBufferSamplers( void )
{
	if (!effect) return;
	//	TODO : use effect params!
	scene->rs->txm->SetTexture( 0, gbuffer[0] );
	scene->rs->txm->SetTexture( 1, gbuffer[1] );
	scene->rs->txm->SetTexture( 2, gbuffer[2] );
	scene->rs->txm->SetTexture( 3, gbuffer[3] );
	scene->rs->txm->SetTexture( 4, gbuffer_depth );
}


//
//	ERSLightRenderer::SetAmbientLevel
//
void ERSLightRenderer::SetAmbientLevel( const EVec4 &color )
{
	if (!effect) return;
	effect->SetVector("ambient_level", &D3DXVECTOR4( color.Ptr() ) );
}


//
//	ERSLightRenderer::SetView
//
void ERSLightRenderer::SetView( const EMatrix4 &view, const EMatrix4 &proj, const EVec4 &view_pos )
{
	if (!effect) return;
	
	EMatrix4 vp		= view * proj;
	EMatrix4 vp_i	= Matrix4Inverse( vp );
	
	effect->SetMatrix("matrix_light_shape_vp",	&D3DXMATRIX(vp.Ptr()));
	effect->SetMatrix("matrix_vp_i",			&D3DXMATRIX(vp_i.Ptr()));
	effect->SetVector("viewer_position",		&D3DXVECTOR4(view_pos.Ptr()));
}


//
//	ERSLightRenderer::SetShadowMapViewProj
//
void ERSLightRenderer::SetShadowMapViewProj( const EMatrix4 &vp )
{
	if (!effect) return;
}


//
//	ERSLightRenderer::SetLight
//
void ERSLightRenderer::SetLight( const ERendLightDesc_s *light )
{
	if (!effect) return;
	SetLightPose( light->position, light->orient );
}


//
//	ERSLightRenderer::SetLightPose
//
void ERSLightRenderer::SetLightPose( const EVec4 &position, const EQuat &orient )
{
	if (!effect) return;
	ASSERT( position.w==1.0f );
	EMatrix4	R	=	QuatToMatrix( orient );
	EMatrix4	T	=	Matrix4Translate( position.x, position.y, position.z );
}



/*-----------------------------------------------------------------------------
	Light shapes :
-----------------------------------------------------------------------------*/

//
//	ERSLightRenderer::DrawOmniLightShape
//
void ERSLightRenderer::DrawOmniLightShape( float radius )
{
	LPDIRECT3DDEVICE9	d3ddev = scene->rs->GetDevice();
	
	struct vertex3dpos_s {
		float x, y, z;
	};

	vertex3dpos_s	cone1[6];
	vertex3dpos_s	cone2[6];
	
	float l = 1.42 * radius;

	cone1[0].x = 0;		cone1[0].y = 0;		cone1[0].z = l;
	cone1[1].x = l;		cone1[1].y =-l;		cone1[1].z = 0;
	cone1[2].x = l;		cone1[2].y = l;		cone1[2].z = 0;
	cone1[3].x =-l;		cone1[3].y = l;		cone1[3].z = 0;
	cone1[4].x =-l;		cone1[4].y =-l;		cone1[4].z = 0;
	cone1[5].x = l;		cone1[5].y =-l;		cone1[5].z = 0;
	
	cone2[0].x = 0;		cone2[0].y = 0;		cone2[0].z =-l;
	cone2[1].x =-l;		cone2[1].y = l;		cone2[1].z = 0;
	cone2[2].x = l;		cone2[2].y = l;		cone2[2].z = 0;
	cone2[3].x = l;		cone2[3].y =-l;		cone2[3].z = 0;
	cone2[4].x =-l;		cone2[4].y =-l;		cone2[4].z = 0;
	cone2[5].x =-l;		cone2[5].y = l;		cone2[5].z = 0;
	
	HRCALL( d3ddev->SetFVF(D3DFVF_XYZ) );
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 4, &cone1, sizeof(vertex3dpos_s)) );
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 4, &cone2, sizeof(vertex3dpos_s)) );
}


//
//	ERSLightRenderer::DrawSpotLightShape
//
void ERSLightRenderer::DrawSpotLightShape( float radius, float spot_radius )
{
	// PROFILER_PROBE();
	
	LPDIRECT3DDEVICE9	d3ddev = scene->rs->GetDevice();
	
	struct vertex3dpos_s {
		float x, y, z;
	};

	vertex3dpos_s	cone_verts[6];
	vertex3dpos_s	cap_verts[4];
	
	float l = radius;
	float r = spot_radius;

	cone_verts[0].x = 0;		cone_verts[0].y = 0;		cone_verts[0].z = 0;
	cone_verts[1].x = r;		cone_verts[1].y =-r;		cone_verts[1].z = -l;
	cone_verts[2].x = r;		cone_verts[2].y = r;		cone_verts[2].z = -l;
	cone_verts[3].x =-r;		cone_verts[3].y = r;		cone_verts[3].z = -l;
	cone_verts[4].x =-r;		cone_verts[4].y =-r;		cone_verts[4].z = -l;
	cone_verts[5].x = r;		cone_verts[5].y =-r;		cone_verts[5].z = -l;
																			
	cap_verts[0].x	=-r;		cap_verts[0].y	= r;		cap_verts[0].z	= -l;
	cap_verts[1].x	= r;		cap_verts[1].y	= r;		cap_verts[1].z	= -l;
	cap_verts[2].x	= r;		cap_verts[2].y	=-r;		cap_verts[2].z	= -l;
	cap_verts[3].x	=-r;		cap_verts[3].y	=-r;		cap_verts[3].z	= -l;

	HRCALL( d3ddev->SetFVF(D3DFVF_XYZ) );
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 4, &cone_verts, sizeof(vertex3dpos_s)) );
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, &cap_verts, sizeof(vertex3dpos_s)) );
}


//
//	ERSLightRenderer::CopyDepthBuffer
//
void ERSLightRenderer::CopyDepthBuffer( void )
{
	if (!effect) return;

	uint n;
	effect->SetTechnique( tech_copy_depth );
	rtm->RestoreRenderTargets();

	SetupGBufferSamplers();

	effect->Begin(&n, 0);
	effect->BeginPass(0);
	
		scene->rs->DrawFSQuad();

	effect->EndPass();
	effect->End();
}


//
//	ERSLightRenderer::RenderAmbient
//
void ERSLightRenderer::RenderAmbient( IPxTexture target )
{
	if (!effect) return;

	uint n;
	HRCALL( effect->SetTechnique( "tech_ambient" ) );

	SetupGBufferSamplers();
	
	rtm->SetRenderTarget(0, target);

	HRCALL( effect->Begin(&n, 0) );
	HRCALL( effect->BeginPass(0) );
	
		scene->rs->DrawFSQuad();

	HRCALL( effect->EndPass() );
	HRCALL( effect->End() );
}



/*-----------------------------------------------------------------------------
	Light itself :
-----------------------------------------------------------------------------*/

//
//	ERSLight::ERSLight
//
ERSLight::ERSLight( ERScene *scene, const ERendLightDesc_s *light_desc )
{											    
	SetVisible(true);
	
	this->scene	=	scene;
	light_rend	=	scene->light_rend;
	this->rtm	=	scene->rs->rtm;
	
	UpdateLight( light_desc );
}


//
//	ERSLight::~ERSLight
//
ERSLight::~ERSLight( void )
{

}


//
//	ERSLight::UpdateLight
//
void ERSLight::UpdateLight( const ERendLightDesc_s *_light_desc )
{
	light_desc	=	*_light_desc;
}


void ERSLight::SetColor( const EVec4 &color )
{
	light_desc.color	=	color;
}

void ERSLight::SetRadius( float radius )
{
	light_desc.radius	=	radius;
}


void ERSLight::SetPose( const EVec4 &position, const EQuat &orient )
{
	light_desc.position	=	position;
	light_desc.orient	=	orient	;
}

void ERSLight::GetPose( EVec4 &position, EQuat &orient ) const
{
	position	=	light_desc.position;
	orient		=	light_desc.orient;
}


void ERSLight::SetVisible( bool visible )
{
	is_visible	=	visible;
}

/*-----------------------------------------------------------------------------
	Light rendering stuff :
-----------------------------------------------------------------------------*/

//
//	ERSLight::RenderLight
//
void ERSLight::RenderLight( IPxTexture target )
{
	if (!is_visible) {
		return;
	}

	ID3DXEffect	*effect = light_rend->effect;
	if (!effect) return;

	effect->SetBool("rs_skip_diffuse",	light_rend->rs_skip_diffuse->Bool());
	effect->SetBool("rs_skip_specular",	light_rend->rs_skip_specular->Bool());
	effect->SetBool("rs_white_diffuse",	light_rend->rs_white_diffuse->Bool());

	//	show debug light shapes :
	//if (light_rend->r_show_lights->Int()) 
	//{
	//	if (light_desc.shape==RS_LIGHT_SHAPE_OMNI) {
	//		DebugOmniShape();
	//	} else 
	//	if (light_desc.shape==RS_LIGHT_SHAPE_SPOT) {
	//		DebugSpotShape();
	//	}
	//}

	////	skip lighting if necessary :	
	//if (light_rend->r_skip_lighting->Int()) {
	//	return;
	//}
	

	if ( light_desc.shape==RS_LIGHT_SHAPE_OMNI ) {
		if (light_desc.shadow) {
			SIGNAL("shadow omni lights are not implemented");
		} else {
			RenderOmniLight( target );
		}
	}
	
	if ( light_desc.shape==RS_LIGHT_SHAPE_SPOT ) {
		if (light_desc.shadow) {
			RenderSpotLightSM( target, light_desc.position, light_desc.orient );
		} else {
			RenderSpotLight( target );
		}
	}
}


//
//	ERSLight::RenderOmniLight
//
void ERSLight::RenderOmniLight( IPxTexture target )
{
	ID3DXEffect	*effect = light_rend->effect;
	if (!effect) return;

	light_rend->SetupGBufferSamplers();
	rtm->SetRenderTarget(0, target);
	
	HRCALL( effect->SetTechnique( "tech_light" ) );
	
	EMatrix4	T = Matrix4Translate( light_desc.position.x, light_desc.position.y, light_desc.position.z );
	EMatrix4	R = QuatToMatrix( light_desc.orient );
	EMatrix4	W = R * T;
	
	HRCALL( effect->SetVector	("light_color",				&D3DXVECTOR4( light_desc.color.Ptr()) ) );
	HRCALL( effect->SetVector	("light_position",			&D3DXVECTOR4( light_desc.position.Ptr()) ) );
	HRCALL( effect->SetFloat	("light_radius",			light_desc.radius ) );
	HRCALL( effect->SetMatrix	("matrix_light_shape_w",	&D3DXMATRIX( W.Ptr() ) ) );
	HRCALL( effect->SetBool		("use_shadows",				FALSE	) );
	
	uint n;
	
	HRCALL( effect->Begin(&n, 0) );
	
	for (uint i=0; i<n; i++) {
		HRCALL( effect->BeginPass(i) );
		
			light_rend->DrawOmniLightShape( light_desc.radius );
	
		HRCALL( effect->EndPass() );
	}
	
	HRCALL( effect->End() );
}


//
//	ERSLight::RenderSpotLight
//
void ERSLight::RenderSpotLight( IPxTexture target )
{
	ID3DXEffect	*effect = light_rend->effect;
	if (!effect) return;

	light_rend->SetupGBufferSamplers();
	rtm->SetRenderTarget(0, target);
	
	effect->SetTechnique( "tech_light" );
	
	EMatrix4	T = Matrix4Translate( light_desc.position.x, light_desc.position.y, light_desc.position.z );
	EMatrix4	R = QuatToMatrix( light_desc.orient );
	EMatrix4	W = R * T;
	
	HRCALL( effect->SetVector	("light_color",				&D3DXVECTOR4( light_desc.color.Ptr()) ) );
	HRCALL( effect->SetVector	("light_position",			&D3DXVECTOR4( light_desc.position.Ptr()) ) );
	HRCALL( effect->SetFloat	("light_radius",			light_desc.radius ) );
	HRCALL( effect->SetMatrix	("matrix_light_shape_w",	&D3DXMATRIX( W.Ptr() ) ) );
	HRCALL( effect->SetBool		("use_shadows",				FALSE	) );
	
	uint n;
	
	HRCALL( effect->Begin(&n, 0) );
	
	for (uint i=0; i<n; i++) {
		HRCALL( effect->BeginPass(i) );
		
			light_rend->DrawSpotLightShape( light_desc.radius, light_desc.spot );
	
		HRCALL( effect->EndPass() );
	}
	
	HRCALL( effect->End() );
}


//
//	ERSLight::RenderSpotLightSM
//
void ERSLight::RenderSpotLightSM( IPxTexture target, const EVec4 &pos, const EQuat &orient )
{
	ID3DXEffect	*effect = light_rend->effect;
	if (!effect) return;

	mask	=	scene->rs->txm->RegisterTexture( light_desc.mask );
	
	//
	//	Render shadow map :
	//
	EMatrix4	view;
	EMatrix4	proj;
	EMatrix4	sm_vp;
	float		zfar	=	light_desc.radius;
	float		znear	=	0.001 * light_desc.radius;
	float		width	=	2 * znear / zfar * light_desc.spot;
	
	proj	=	Matrix4PerspectiveRH(width, width, znear, zfar);
	view	=	Matrix4Translate( -pos.x, -pos.y, -pos.z ) * QuatToMatrix( QuatInverse( orient ) ) ;
	sm_vp	=	view * proj;

	scene->RenderShadowMap(view, proj, light_rend->GetSMColor(), light_rend->GetSMDepth());
	
	//
	//	Render light :
	//	
	light_rend->SetupGBufferSamplers();
	rtm->SetRenderTarget(0, target);
	
	HRCALL( effect->SetTechnique( "tech_light_sm" ) );

	//	compute light shape matrix :
	EMatrix4	T = Matrix4Translate( light_desc.position.x, light_desc.position.y, light_desc.position.z );
	EMatrix4	R = QuatToMatrix( light_desc.orient );
	EMatrix4	W = R * T;

	//	setup shader :	
	HRCALL( effect->SetVector	("light_color",				&D3DXVECTOR4( light_desc.color.Ptr()) ) );
	HRCALL( effect->SetVector	("light_position",			&D3DXVECTOR4( light_desc.position.Ptr()) ) );
	HRCALL( effect->SetFloat	("light_radius",			light_desc.radius ) );
	HRCALL( effect->SetMatrix	("matrix_light_shape_w",	&D3DXMATRIX( W.Ptr() ) ) );
	HRCALL( effect->SetMatrix	("matrix_sm_vp",			&D3DXMATRIX( sm_vp.Ptr() ) ) );
	HRCALL( effect->SetBool		("use_shadows",				TRUE	) );

	light_rend->scene->rs->txm->SetTexture( 6, light_rend->GetSMDepth() );
	light_rend->scene->rs->txm->SetTexture( 7, mask );
	
	uint n;
	
	HRCALL( effect->Begin(&n, 0) );
	
	for (uint i=0; i<n; i++) {
		HRCALL( effect->BeginPass(i) );
		
			light_rend->DrawSpotLightShape( light_desc.radius, light_desc.spot );
	
		HRCALL( effect->EndPass() );
	}
	
	HRCALL( effect->End() );
}

/*-----------------------------------------------------------------------------
	Debugging stuff :
-----------------------------------------------------------------------------*/

//
//	ERSLight::DebugOmniShape
//
void ERSLight::DebugOmniShape( void )
{
	EVec3	pos( light_desc.position.x, light_desc.position.y, light_desc.position.z );
	scene->DebugLine( pos - EVec3(1,0,0), pos + EVec3(1,0,0),  light_desc.color );
	scene->DebugLine( pos - EVec3(0,1,0), pos + EVec3(0,1,0),  light_desc.color );
	scene->DebugLine( pos - EVec3(0,0,1), pos + EVec3(0,0,1),  light_desc.color );

	float r	=	light_desc.radius;
	EVec4 c =	light_desc.color;

	for (uint i=0; i<32; i++) {
		float da =  2 * PI / 32.0f;
		float a  =  i * da;
		EVec4 v0 =	r * EVec4(cos(a),    sin(a),    0, 0);
		EVec4 v1 =	r * EVec4(cos(a+da), sin(a+da), 0, 0);
		v0 = QuatRotateVector( v0, light_desc.orient ) + light_desc.position;
		v1 = QuatRotateVector( v1, light_desc.orient ) + light_desc.position;
		
		scene->DebugLine( EVec3(v0.x, v0.y, v0.z), EVec3(v1.x, v1.y, v1.z), c );
	}
	
	for (uint i=0; i<32; i++) {
		float da =  2 * PI / 32.0f;
		float a  =  i * da;
		EVec4 v0 =	r * EVec4(0, cos(a),    sin(a),    0);
		EVec4 v1 =	r * EVec4(0, cos(a+da), sin(a+da), 0);
		v0 = QuatRotateVector( v0, light_desc.orient ) + light_desc.position;
		v1 = QuatRotateVector( v1, light_desc.orient ) + light_desc.position;
		
		scene->DebugLine( EVec3(v0.x, v0.y, v0.z), EVec3(v1.x, v1.y, v1.z), c );
	}
	
	for (uint i=0; i<32; i++) {
		float da =  2 * PI / 32.0f;
		float a  =  i * da;
		EVec4 v0 =	r * EVec4(cos(a),    0, sin(a),    0);
		EVec4 v1 =	r * EVec4(cos(a+da), 0, sin(a+da), 0);
		v0 = QuatRotateVector( v0, light_desc.orient ) + light_desc.position;
		v1 = QuatRotateVector( v1, light_desc.orient ) + light_desc.position;
		
		scene->DebugLine( EVec3(v0.x, v0.y, v0.z), EVec3(v1.x, v1.y, v1.z), c );
	}
}


//
//	ERSLight::DebugSpotShape
//
void ERSLight::DebugSpotShape( void )
{
	EVec3	pos( light_desc.position.x, light_desc.position.y, light_desc.position.z );
	scene->DebugLine( pos - EVec3(1,0,0), pos + EVec3(1,0,0),  light_desc.color );
	scene->DebugLine( pos - EVec3(0,1,0), pos + EVec3(0,1,0),  light_desc.color );
	scene->DebugLine( pos - EVec3(0,0,1), pos + EVec3(0,0,1),  light_desc.color );

	float r	=	light_desc.spot;
	float d =	light_desc.radius;
	EVec4 c =	light_desc.color;

	for (float f = 0.1f; f<1.0f; f += 0.1f) {
		for (uint i=0; i<32; i++) {
			float da =  2 * PI / 32.0f;
			float a  =  i * da;
			EVec4 v0 =	f * EVec4(r*cos(a),    r*sin(a),    -d, 0);
			EVec4 v1 =	f * EVec4(r*cos(a+da), r*sin(a+da), -d, 0);
			v0 = QuatRotateVector( v0, light_desc.orient ) + light_desc.position;
			v1 = QuatRotateVector( v1, light_desc.orient ) + light_desc.position;
			
			scene->DebugLine( EVec3(v0.x, v0.y, v0.z), EVec3(v1.x, v1.y, v1.z), c );
		}
	}
}
